// 公共方法
import app from '@/main'
import {  getUserHomepage } from '@/api/basic';
const OSS = require('ali-oss');
import { HTTP_REQUEST_URL } from '@/config/app';
//判断头像是否为base64
export const isBase64 = (str) => {
	if (!str) return
	let str1 = str;
	if (typeof str == 'object') {
		str1 = str['url']
	}
	return !!(str1.includes("data:image") && str1.includes(";base64,"));
}
//拼接前缀url
export const ImageUrl = (url) => {
	return isBase64(url) ? url : IMAGE_URL + url
}
//毫秒转时间(秒和毫秒）
export const time = (type = "MS", date1, str = "year", gap = ".") => {
	if (!date1) return "--";
	if (type === "S") date1 = date1 * 1000 //秒
	let year = new Date(date1).getFullYear();
	let month = (new Date(date1).getMonth() + 1) > 9 ? (new Date(date1).getMonth() + 1) : '0' + (new Date(date1)
		.getMonth() + 1);
	let date = new Date(date1).getDate() > 9 ? new Date(date1).getDate() : '0' + new Date(date1).getDate();
	let hours = new Date(date1).getHours() > 9 ? new Date(date1).getHours() : '0' + new Date(date1).getHours();
	let minutes = new Date(date1).getMinutes() > 9 ? new Date(date1).getMinutes() : '0' + new Date(date1)
		.getMinutes();
	let seconds = new Date(date1).getSeconds() > 9 ? new Date(date1).getSeconds() : '0' + new Date(date1)
		.getSeconds();
	if (str === "year") {
		return `${year}${gap}${month}${gap}${date} ${hours}:${minutes}:${seconds}`
	}
	if (str === "date") {
		return `${year + gap + month + gap + date}`
	}
	return `${year + gap + month + gap + date} ${hours}:${minutes}:${seconds}`
}
//判断是否为对象
export const isObject = (obj) => {
	return Object.prototype.toString.call(obj) === '[object Object]'
}

// H5 app iframe传值兼容
// onNativeShow onNativeHide
// 1. 本身是翻译就不用翻译了  2 同国家不需要翻译
/**
 * anthor liyingqi
 *  834777203@qq.com
 * action goHome  data mineFragment 我的 msgFragment 消息 workFragment 工作台 homeFragment 首页
 * action call  data "{userId: '',type: 1}"用户id 类型 1需要翻译 2 不需要翻译  打视频
 * action initiateChat  data 用户id 聊天
 *  action aliPay  data 支付宝数据  
 * action wxPay  data 微信支付数据
 * action openLive  data "{id: ''}"// 开播 展会id
 * action joinLive data "{userId: '',id: ''}"// 加入直播间 展会id
 * action login  // 登录
 * activeLogin
 * action downloadFile data:{url: ''} // 下载文件
 * action makePhoneCall data: string // 拨打电话
 * action sendGood  data: {url: string,title: string,title_ru: string,currency: string,price: string, good_id: number,pic: string, userId: string}  currency: 货币单位 // 发送小样
 * action getCurrentPosition 
 */

export const isMessageGo = (params) => {
	/**
	 * 检查是否需要显示翻译功能提示对话框
	 * 当用户尝试进行通话、开播或加入直播时，提示用户保持环境安静并关闭麦克风
	 * @param {Object} params - 传递的参数对象
	 * @param {Boolean} params.isLock - 是否已经显示过提示框
	 * @param {String} params.action - 操作类型：'call'、'openLive'或'joinLive'
	 * @returns {undefined} - 如果需要显示提示框，函数会提前返回
	 */
	if (!params.isLock && (params.action == 'call' || params.action == 'openLive' || params.action == 'joinLive')) {
		let lang = uni.getStorageSync('lang');
		uni.showModal({
			title: lang == 'zh'?'GLUZ支持通话翻译':'GLUZ поддерживает перевод звонков',
			content: lang == 'zh'?'请保持环境安静，不说话时关闭麦克风，以确保翻译功能正常运行。':'Пожалуйста, соблюдайте тишину в окружающей среде, выключайте микрофон, когда не говорите, чтобы обеспечить нормальную работу функции перевода.',
			confirmText: lang == 'zh'?'确定':'ОК',
			cancelText: lang == 'zh'?'取消':'Отмена',
			success: (res) => {
				if (res.confirm) {
					isMessageGo({
						...params,
						isLock: true
					})
				}
			}
		})
		return;
	}



	params.webview = params.webview || 'zWebViewShop';
	if (window.NativeBridge) {
		if (window.NativeBridge.postMessage) {
			try {
				window.NativeBridge.postMessage(JSON.stringify(params)); // app 交互 postmessage需要json
			} catch (error) {
				console.log(error.message, ' error.message')
			}
		}
	} else if (window.webkit) {
		if (window.webkit.messageHandlers && window.webkit.messageHandlers.NativeBridge) {
			try {
				window.webkit.messageHandlers.NativeBridge.postMessage(JSON.stringify(params)); // app 交互 postmessage需要json
			} catch (error) {
				console.log(error.message, ' error.message')
			}
		}
	} else {
		if (typeof plus == 'undefined') {
			window.parent.postMessage(params, "*");
		} else {
			uni.webView.postMessage({
				data: params
			});
		}
	}

}



// 判断是否登录
export const isLogin = () => {
	const token = uni.getStorageSync('xzdToken') || "";
	const mobile = uni.getStorageSync('mobile');
	if (!token || !mobile) {
		uni.showToast({
			title: app.$i18n.t('请先登录'),
			icon: 'none'
		})
		uni.clearStorage();
		uni.clearStorageSync();
		isMessageGo({
			action: 'activeLogin'
		})
		return false;
	} else {
		return true;
	}
}


/**
 * 
 * anthor liyingqi
 *  834777203@qq.com
 * desc 文件上传
 */
// 阿里云直传
let sign =  {
	accessKeyId: 'LTAI5tJzTZBzFkjYiLTmn1Ca',
	accessKeySecret: 'M4LiEM0ZnUxtT0dV537nHL33ODjw7q',
	bucket: 'gluz-oss',
	endpoint: 'oss-cn-beijing.aliyuncs.com',
	cdnUrl: 'https://gluz-oss.oss-cn-beijing.aliyuncs.com'
}

function generateUniqueName(name='123.png') {
	console.log(name,'name')
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1000000); // 6位随机数
  return `${timestamp}${random}.${name?.split('.')[name?.split('.').length - 1]}`;
}

export const uploadFile = (file) => {
	let lang = uni.getStorageSync('lang');
	return new Promise((reslove, reject) => {
		uni.showLoading({ title: 'loading...', mask: true });
		let client = new OSS({
			region: 'oss-cn-beijing', // 上传后的域名
			accessKeyId: sign.accessKeyId, // 后台的临时签名ID
			accessKeySecret: sign.accessKeySecret, // 后台的临时签名密钥
			bucket: 'gluz-oss', // OSS仓库名
	 	});

		let curTime = new Date();
		let year = curTime.getFullYear();
		let month = curTime.getMonth() + 1;
		let day = curTime.getDate();
    const fileName = `/imgs/${year}${month}${day}/${generateUniqueName(file.name)}`;
		try {
			client.multipartUpload(fileName, file).then(ress=>{
				let response = ress.res;
				if (response.status == 200){
					if (ress.name){
						let url = `${sign.cdnUrl}${ress.name}`;
						reslove({
							fullurl: url,
							url: ress.name
						})
						uni.hideLoading();
					} else {
						uni.hideLoading();
						reject(lang == 'zh'?'上传失败':'Ошибка загрузки')
					}
				} else {
					reject(lang == 'zh'?'上传失败':'Ошибка загрузки')
					uni.hideLoading();
				}
				console.log(ress,'ressressress');//此处就已经上传成功了
			}).catch(err=>{
				reject(lang == 'zh'?'上传失败':'Ошибка загрузки')
				uni.hideLoading();
			})
		} catch (error) {
			reject(lang == 'zh'?'上传失败':'Ошибка загрузки')
			uni.hideLoading();
		}
		



		// uni.showLoading({ title: '上传中...', mask: true });
		// uni.uploadFile({
		// 	url: 'https://app.gluz.com.cn/api/common/upload', // 替换为实际接口
		// 	filePath: file.path,
		// 	name: 'file',
		// 	success: (res) => {
		// 		uni.hideLoading();
		// 		if (res.statusCode === 200) {
		// 			var json = JSON.parse(res.data)

		// 			if (json.code == 1) {
		// 				reslove(json.data)
		// 			} else {
		// 				uni.showToast({
		// 					title: json.msg,
		// 					icon: 'none'
		// 				})
		// 			}
		// 			// 处理返回数据
		// 		} else {
		// 			uni.showToast({ title: '上传失败', icon: 'none' });
		// 			reject('上传失败')
		// 		}
		// 	},
		// 	fail: (err) => {
		// 		uni.hideLoading();
		// 		uni.showToast({ title: '上传出错', icon: 'none' });
		// 		reject('上传失败')
		// 	}
		// });
	})

};


/**
 * 
 * anthor liyingqi
 *  834777203@qq.com
 * desc 图片视频选择封装
 * parmas  type 文件类型 size 文件尺寸限制
 */

const checkFileType = (type, accept = ['image/jpeg', 'image/png', 'image/jpg']) => {
	const allowedTypes = accept;
	return allowedTypes.includes(type.toLowerCase());
}

const checkFileSize = (size, limit = 5) => {
	const maxSize = limit * 1024 * 1024;
	return size <= maxSize;
}

export const chooseFile = ({ type, size, count }) => {
	let lang = uni.getStorageSync('lang');
	return new Promise((reslove, reject) => {
		switch (type) {
			case 'image':
				uni.chooseImage({
					count: 1, // 最多选择数量
					sourceType: ['album', 'camera'], // 来源为相册或相机
					success: (res) => {
						const file = res.tempFiles[0];
						// 检查文件类型
						if (!checkFileType(file.type)) {
							uni.showToast({ title: lang == 'zh'?'支持jpeg、jpg、png':'Поддерживаются jpeg, jpg, png', icon: 'none' });
							return;
						}
						// 检查文件大小
						if (!checkFileSize(file.size, size)) {
							uni.showToast({ title: lang == 'zh'?`图片大小不能超过${size}MB`:`Размер изображения не может превышать ${size}MB`, icon: 'none' });
							return;
						}
						reslove(file)
					},
					fail: (err) => {
						reject(err)
					}
				})
				break;
			case 'video':
				uni.chooseVideo({
					count,
					sourceType: ['album', 'camera'],
					success: (res) => {
						const file = res.tempFile;
						// 检查文件类型
						if (!checkFileType(file.type, ['video/mp4', 'video/rmvb', 'video/avi','video/quicktime'])) {
							uni.showToast({ title: lang == 'zh'?`支持mp4、rmvb、AVI`:`Поддерживаются mp4, rmvb, AVI`, icon: 'none' });
							return;
						}
						// 检查文件大小
						if (!checkFileSize(file.size, size)) {
							uni.showToast({ title: lang == 'zh'?`视频大小不能超过${size}MB`:`Размер видео не может превышать ${size}MB`, icon: 'none' });
							return;
						}
						file.path = res.tempFilePath;
						reslove(file)
					},
					fail: (err) => {
						reject(err)
					}
				})
				break;
		}
	})


}

// 结束

/**
 * 根据国家ID获取国家信息
 * @param id 国家ID
 * @returns 返回对应的国家信息对象,包含name(国家名称)、imgurl(国旗图片路径)、id(国家ID)
 * @example
 * const country = createNational(0); 
 * // 返回 {name: '中国', imgurl: '/static/country/2.png', id: 0}
 */
export const createNational = (id) => {
	const nationals = [
		{
			name: '中国',
			imgurl: "/static/country/2.png",
			id: 0,
		},
		{
			name: '俄罗斯',
			imgurl: "/static/country/8.png",
			id: 1,
		},
		{
			name: '哈萨克斯坦',
			imgurl: "/static/country/6.png",
			id: 2,
		},
		{
			name: '白俄罗斯',
			imgurl: "/static/country/3.png",
			id: 3,
		},
		{
			name: '吉尔吉斯斯坦',
			imgurl: "/static/country/4.png",
			id: 4,
		},
		{
			name: '乌兹别克斯坦',
			imgurl: "/static/country/5.png",
			id: 5,
		},
		{
			name: '土库曼斯坦',
			imgurl: "/static/country/1.png",
			id: 6,
		},
		{
			name: '乌克兰',
			imgurl: "/static/country/7.png",
			id: 7,
		},
		{
			name: '塔吉克斯坦',
			imgurl: "/static/country/9.png",
			id: 8,
		},
	];
	return nationals.find(item => item.id === id) ? nationals.find(item => item.id === id) : nationals[0];
}


/**
 * 根据国家ID获取国家信息
 * @param id 国家ID
 * @returns 返回对应的国家信息对象,包含name(国家名称)、imgurl(国旗图片路径)、id(国家ID)
 * @example
 * const country = createNational(0); 
 * // 返回 {name: '中国', imgurl: '/static/country/2.png', id: 0}
 */
export const createNationalCircle = (id) => {
	const nationals = [
		{
			name: '中国',
			imgurl: "/static/circle/2.png",
			id: 0,
		},
		{
			name: '俄罗斯',
			imgurl: "/static/circle/8.png",
			id: 1,
		},
		{
			name: '哈萨克斯坦',
			imgurl: "/static/circle/6.png",
			id: 2,
		},
		{
			name: '白俄罗斯',
			imgurl: "/static/circle/3.png",
			id: 3,
		},
		{
			name: '吉尔吉斯斯坦',
			imgurl: "/static/circle/4.png",
			id: 4,
		},
		{
			name: '乌兹别克斯坦',
			imgurl: "/static/circle/5.png",
			id: 5,
		},
		{
			name: '土库曼斯坦',
			imgurl: "/static/circle/1.png",
			id: 6,
		},
		{
			name: '乌克兰',
			imgurl: "/static/circle/7.png",
			id: 7,
		},
		{
			name: '塔吉克斯坦',
			imgurl: "/static/circle/9.png",
			id: 8,
		},
	];
	return nationals.find(item => item.id === id) ? nationals.find(item => item.id === id) : nationals[0];
}



/**
 * 根据会员等级获取会员信息
 * @param level 会员等级
 * @returns 返回对应会员信息对象,包含name(会员名称)、imgurl(会员图片路径)、id(会员等级)
 * @example
 * const member = memberLevel(0);    
 * // 返回 {name: '普通会员', imgurl: '/static/img/member1.png', id: 0}
 */
export const memberLevel = (level = 0) => {
	level = level === null ? 0 : level;
	let levels = [
		{
			name: '普通会员',
			imgurl: "/static/work/member0.png",
			id: 0,
		},
		{
			name: '黄金会员',
			imgurl: "/static/work/member1.png",
			id: 1,
		},
		{
			name: '铂金会员',
			imgurl: "/static/work/member2.png",
			id: 2,
		},
		{
			name: '钻石会员',
			imgurl: "/static/work/member3.png",
			id: 3,
		},
	]
	return levels.find(item => item.id === level) ? levels.find(item => item.id === level) : levels[0];
}



// token拦截 1212
export const validToken = () => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${HTTP_REQUEST_URL}/user/check_token`, //接口地址：前缀+方法中传入的地址
			method: 'POST', //请求方法：传入的方法或者默认是“GET”
			data: {
				user_id: uni.getStorageSync('user_id'),
				token: uni.getStorageSync('xzdToken')
			}, //传递参数：传入的参数或者默认传递空集合
			success: (res) => {
				if (res.data.code == 4001) {
					reject(res);
					isMessageGo({
						action: 'login',
					})
				}
				resolve(res)
			},
			// 这里的接口请求，如果出现问题就输出接口请求失败

			fail: (err) => {
				resolve(err)
			}
		})
	})

}



// 将对象转为query
export function objectToQueryString(obj, prefix) {
	const parts = [];

	for (const key in obj) {
		if (!obj.hasOwnProperty(key)) continue;
		const value = obj[key];
		const encodedKey = encodeURIComponent(key);
		const fullKey = prefix ? `${prefix}[${encodedKey}]` : encodedKey;

		if (value !== null && typeof value === 'object') {
			// 处理数组或对象
			const nested = objectToQueryString(value, fullKey);
			if (nested) parts.push(nested);
		} else {
			// 处理基本类型
			if (value !== null && value !== undefined) {
				parts.push(`${fullKey}=${encodeURIComponent(value)}`);
			}
		}
	}

	return '?' + parts.join('&');
}

// 未认证跳转拦截
export const unAuthRedirect = async () => {
	const lang = uni.getStorageSync('lang');
	return new Promise(async (resolve, reject) => {
		try {
			const res = await getUserHomepage({
				user_id: uni.getStorageSync('user_id'),
			})
			if (res.data.code == 1) {
				let userInfo = res.data.data.userInfo || {};
				let identity_type = userInfo.identity_type;
				let is_audit = userInfo.is_audit;// 0 未认证 1 审核中 2认证成功 3认证失败
				if (identity_type == 11) { // 翻译取用户信息里面的认证
					is_audit = userInfo.user_staff.is_renzheng;
				}
				if (identity_type == 8) {
					is_audit = 2;
				}
				switch (+is_audit) {
					case 0: // 未认证
					case 1: // 审核中
					case 3: // 认证失败

						let modelObj = {};
						if (is_audit == 0) {
							modelObj = {
								content: lang == 'zh'?'您还未认证,请去认证？':'Вы еще не прошли верификацию, пожалуйста, пройдите ее?',
								confirmText: lang == 'zh'?'去认证':'Выбрать',
							}
						}
						if (is_audit == 1) {
							modelObj = {
								content: lang == 'zh'?'认证正在审核中，请耐心等待？':'В ходе проверки информации...',
								confirmText: lang == 'zh'?'重新认证':'Выбрать',
							}
						}
						if (is_audit == 3) {
							modelObj = {
								content: lang == 'zh'?'认证失败，请重新认证？':'Вы еще не прошли верификацию, пожалуйста, пройдите ее?',
								confirmText: lang == 'zh'?'重新认证':'Выбрать',
							}
						}
						console.log('identity_type',identity_type)
						if (identity_type==0) {
							uni.showModal({
								title: 	lang == 'zh'?'提示':'Предупреждение',
								cancelText: lang == 'zh'?'取消':'Отмена',
								...modelObj,
								success: (res) => {
									if (res.confirm) {
										switch (+identity_type) {
											case 1: // 供应商
											case 0:
												uni.navigateTo({
													url: `/pages/suppire/index?identity_id=${userInfo.identity_id}&is_renzheng=${is_audit}`,
													webview: 'zWebView'
												})
												break;
											case 3: // 采购商
											case 12: // 个人
												uni.navigateTo({
													url: `/pages/caigou/index?identity_id=${userInfo.identity_id}&is_renzheng=${is_audit}&identity_type=${identity_type}`,
													webview: 'zWebView'
												})
												break;
											case 2:
											case 5:
											case 6:
											case 7:
												var u_id = userInfo.user_id
												uni.navigateTo({
													url: `/pages/forwardingInformation/businessCardInput?u_id=` + u_id,
													webview: 'zWebView'
												})
												break;
	
											case 9: // 服务商
											case 4:
												uni.navigateTo({
													url: `/pages/fuwu/index?identity_id=${userInfo.identity_id}&is_renzheng=${is_audit}`,
													webview: 'zWebView'
												})
												break;
											case 11: //翻译
											case 10: //翻译
												uni.navigateTo({
													url: `/pages/translate/authTranslate/index?is_renzheng=${is_audit}`,
													webview: 'zWebView'
												})
												break;
										}
										reject(false)
									}
								}
							})
						} else {
							resolve(true)
						}
					
						break;
					// case 1: // 审核中
					// 	resolve(true)
					// 	break;
					case 2: // 认证成功
						resolve(true)
						break;

				}
			}
		} catch (error) {
			reject(false)
		}
	})

}





// 会员权限拦截

export const vipPrivilegeGet= (idType,noToast = false,isHide = false)=> {
	const lang = uni.getStorageSync('lang')
	let list = uni.getStorageSync('vipList') || [];
	let level = uni.getStorageSync('level');

	let item = list.find((ele)=>{
		return idType.includes(ele.name)
	})
	if(item) {
		let isSuccess = false;
		let b = 0;
		for(let i = 0; i < item.arr.length; i++) {
			if(item.arr[i].level == level && (item.arr[i].state == 0 &&item.arr[i].value == 1 || item.arr[i].state == 1 && item.arr[i].content)) {
				isSuccess = true;
			}
			// 如何值存在
			if (!(item.arr[i].state == 0 &&item.arr[i].value == 1 || item.arr[i].state == 1 && item.arr[i].content)) {
				b++;
			}

		}
		let arr = item.arr.reverse();
		let tipsIndex = arr.findIndex((ele)=> (ele.state == 0 &&ele.value == 1 || ele.state == 1 && ele.content))
		if (isHide){
			if (b == item.arr.length){ // 如果所有等级都没权限隐藏，则返回true
				return false;
			} else {
				return true;
			}
		}
	
		if(isSuccess) {
			return true;
		} else {
			if(!noToast) {
				uni.showToast({
					title: lang == 'zh'?`此功能为${['普通会员','黄金会员','铂金会员','钻石会员'][tipsIndex]}功能，请开通${['普通会员','黄金会员','铂金会员','钻石会员'][tipsIndex]}后查看。`: `Эта функция является${['Обычный','Золотой','Платина','Бриллиант'][tipsIndex]}функцией, пожалуйста, активируйте${['Обычный','Золотой','Платина','Бриллиант'][tipsIndex]}для просмотра.`,
					icon: 'none'
				})
			}
			return false;
		}
	} else {
		return true;
	}
}

